package cn.crism.chatme.netty;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;

public class WSServerInitalizer extends ChannelInitializer<SocketChannel>{

	@Override
	protected void initChannel(SocketChannel ch) throws Exception {
		ChannelPipeline pipeline = ch.pipeline();
		
		// Websocket 基于http协议 需要http编解码器
		pipeline.addLast(new HttpServerCodec());
		// 对写大数据流的支持
		pipeline.addLast(new ChunkedWriteHandler());
		// 对httpMessage进行聚合，聚合成 FullHttpRequest 或者 FullHttpResponse
		pipeline.addLast(new HttpObjectAggregator(1024*64));
		
		// ========以上用于支持http协议========= //


		// =========添加心跳 start======== //

		pipeline.addLast(new IdleStateHandler(22,25,50));

		pipeline.addLast(new HeartBeatHandler());





		// websocket 服务器处理的协议  用于指定客户端连接的路由  /ws
		// 处理握手操作 handshaking as well as processing of control frames (Close, Ping, Pong) 心跳机制
		pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
		

		pipeline.addLast(new ChatHandler());
	}

}
